#!/bin/bash

# table-csv2xml.sh
# 
# Script to format the CSV tables produced by make-tables.R into XML
# that we can put on our website.
#
# Syntax
#
#    ./table-csv2xml.sh table1.csv [table2.csv ...]
#
# The output for file table1.csv is saved to table1.xml, etc.
#
# v0.2  20 Sep 2007
#
# Author: Ramon Casero <ramon.casero@oucs.ox.ac.uk>
# Copyright © 2007 University of Oxford
#
# This file is part of mta-tracker.
#
# mta-tracker is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mta-tracker is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mta-tracker.  If not, see <http://www.gnu.org/licenses/>.
#
# ChangeLog
#
# * 2008-08-21 (rcasero):
#
#   ** Upgrade licence to GPL v3.
#
# * 2007-09-20 (rcasero): v0.2.
#
#   ** Add fixed width to tables.
#
# * 2007-08-10 (rcasero): v0.1.
#
#   ** First running version.

# syntax message
usage() {
    echo "Syntax: `basename $0` table1.csv [table2.csv ...]"
}

# check number of input arguments
if [ $# -lt 1 ]
    then
    usage
    exit 1
fi

# iterate through input arguments
for table
  do

  # check that file exists
  if [ -e "$table" ]
      then
      echo Table file: "$table" 1>&2
  else
      echo Warning! File cannot be found, skipping: "$table" 1>&2
      continue
  fi
  
  # get output file name
  tableout=${table%.csv}.xml
  echo $tableout

  # get number of rows and columns in the table
  NROW=`wc -l "$table"`
  NROW=${NROW% *}
  NROW=`expr $NROW - 1`
  NCOL=`grep ',' -om 1 "$table" | wc -l`
  NCOL=`expr $NCOL + 1`

  echo Size: $NROW rows, $NCOL cols

  # get caption
  CAPT=`head -n 1 "$table"`

  (
      # table header
      echo '<table border="1" width="80%" cols="'$NCOL'" rend="boxed" rows="'$NROW'">'
      echo '<head>'$CAPT'</head>'

      # column headers
      grep '^,' "$table" \
	  | sed 's/$/<\/hi><\/cell><\/row>/' \
	  | sed 's/^,/<row role="label"><cell><hi><\/hi><\/cell><cell align="center"><hi>/' \
	  | sed 's/,/<\/hi><\/cell><cell align="center"><hi>/g' \
	  | sed 's/<\/cell>/<\/cell>\n/g'

      # data cells
      tail -n `expr $NROW - 1` "$table" \
	  | sed 's/$/<\/cell><\/row>/' \
	  | sed 's/^/<row role="data"><cell align="left">/' \
	  | sed 's/,/<\/cell><cell align="right">/g' \
	  | sed 's/<\/cell>/<\/cell>\n/g'

      echo '</table>'
  ) > "$tableout"
done
